import http from "@/http/index.ts"
import {IncreaseMachinePricing, IncreaseMachinePricingQueryDto, IncreaseMachinePricingBatchCopyDto} from './type.ts'

// 新增提升机核价
export const addApi = (data: IncreaseMachinePricing) => {
    return http.post("/increaseMachinePricing/createIncreaseMachinePricing", data)
}

// 获取价格
export const getPriceApi = (data: IncreaseMachinePricing) => {
    return http.post("/increaseMachinePricing/getPrice", data)
}

// 分页条件查询列表
export const getListApi = (data: IncreaseMachinePricingQueryDto) => {
    return http.get("/increaseMachinePricing/getIncreaseMachinePricingList", data)
}

// 编辑提升机核价
export const editApi = (data: IncreaseMachinePricing) => {
    return http.put("/increaseMachinePricing/updateIncreaseMachinePricing", data)
}

// 删除提升机核价
export const deleteApi = (id: number) => {
    return http.delete(`/increaseMachinePricing/deleteIncreaseMachinePricing/${id}`)
}

// 批量删除提升机核价
export const batchDeleteApi = (ids: number[]) => {
    return http.post("/increaseMachinePricing/batchDelete", { ids })
}

// 导入提升机核价
export const importIncreaseMachinePricing = (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return http.upload("/increaseMachinePricing/import", formData)
}

// 导出提升机核价（返回blob）
export const exportIncreaseMachinePricing = (params?: any) => {
    // 构建查询字符串
    const queryString = params ? new URLSearchParams(
        Object.entries(params).reduce((acc, [key, value]) => {
            if (value !== undefined && value !== null && value !== '') {
                acc[key] = String(value);
            }
            return acc;
        }, {} as Record<string, string>)
    ).toString() : '';
    
    const url = `${http['instance'].defaults.baseURL}/increaseMachinePricing/export${queryString ? '?' + queryString : ''}`;
    window.location.href = url;
    return Promise.resolve();
}

// 下载导入模板（返回blob）
export const downloadTemplate = () => {
    const url = `${http['instance'].defaults.baseURL}/increaseMachinePricing/downloadTemplate`
    window.location.href = url
    return Promise.resolve()
}

// 更新提升机核价状态
export const updateStatusApi = (params: { id: number; activate: number }) => {
    return http.put('/increaseMachinePricing/updateStatus', params)
}

// 批量更新提升机核价状态
export const batchUpdateStatusApi = (params: { ids: number[], activate: number }) => {
    return http.put("/increaseMachinePricing/batchUpdateStatus", params)
}

// 获取可导出字段列表
export const getExportFieldsApi = () => {
    return http.get('/increaseMachinePricing/getExportFields')
}

// 自定义导出提升机核价
export const exportCustomIncreaseMachinePricingApi = (exportRequest: any) => {
    return http.post('/increaseMachinePricing/exportCustom', exportRequest, {
        responseType: 'blob'
    }).then(response => {
        console.log('收到自定义导出响应:', response)
        console.log('响应类型:', typeof response)
        console.log('响应是否为Blob:', response instanceof Blob)
        
        // HTTP拦截器对于blob类型返回完整的response对象，需要获取response.data
        let blobData: Blob;
        const responseAny = response as any;
        if (responseAny && typeof responseAny === 'object' && 'data' in responseAny) {
            // 如果是完整的response对象，获取data属性
            blobData = responseAny.data;
        } else if (responseAny && responseAny instanceof Blob) {
            // 如果直接是Blob对象
            blobData = responseAny;
        } else {
            console.error('响应不是预期的格式:', response)
            throw new Error('导出响应格式错误')
        }
        
        // 检查是否是Blob对象
        if (!(blobData instanceof Blob)) {
            console.error('响应数据不是Blob类型:', blobData)
            throw new Error('导出响应格式错误')
        }
        
        // 检查blob大小
        if (blobData.size === 0) {
            throw new Error('导出文件为空')
        }
        
        // 检查是否是错误响应（JSON格式）
        if (blobData.type.includes('application/json') || blobData.type.includes('text/plain')) {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()
                reader.onload = function() {
                    try {
                        const responseText = reader.result as string
                        console.log('错误响应内容:', responseText)
                        
                        // 尝试解析为JSON
                        const errorData = JSON.parse(responseText)
                        reject(new Error(errorData.message || '导出失败'))
                    } catch (parseError) {
                        // 如果不是有效的JSON，直接使用文本内容
                        const responseText = reader.result as string
                        reject(new Error(responseText || '导出失败'))
                    }
                }
                reader.onerror = function() {
                    reject(new Error('读取错误响应失败'))
                }
                reader.readAsText(blobData)
            })
        }
        
        // 创建下载链接并触发下载
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blobData)
        link.download = `提升机核价自定义导出_${new Date().getTime()}.xlsx`
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
        
        console.log('自定义导出完成，文件大小:', blobData.size, 'bytes')
        return Promise.resolve()
    }).catch(error => {
        console.error('自定义导出失败:', error)
        throw error
    })
}

// 批量复制提升机核价
export const batchCopyApi = (params: IncreaseMachinePricingBatchCopyDto) => {
    return http.post('/increaseMachinePricing/batchCopy', params)
} 